'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: oauth_handler.py
* @Time: 2025/10/11
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass
from injector import inject

from internal.schema.oauth_schema import AuthorizeReq, AuthorizeResp
from internal.service import OauthService
from pkg.response import success_json, validate_error_json


@inject
@dataclass
class OAuthHandler:
    """第三方认证处理器"""
    oauth_service:OauthService

    def provider(self, provider_name:str):
        """根据传递的名字获取服务商重定向地址"""
        #1、根据传递的provider_name获取服务提供商
        oauth = self.oauth_service.get_oauth_by_provider_name(provider_name)

        #2、调用函数获取授权地址
        redirect_url = oauth.get_authorization_url()
        return success_json({"redirect_url":redirect_url})

    def authorize(self, provider_name:str):
        """根据传递的提供商名字 + code 获取第三方信息"""
        #1、提取数据并校验
        req = AuthorizeReq()
        if not req.validate:
            return validate_error_json(req.errors)

        #2、调用服务登录账号
        credential = self.oauth_service.oauth_login(provider_name, req.code.data)
        return success_json(AuthorizeResp().dump(credential))